package com.mayikt.member.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSONObject;
import com.mayikt.base.BaseApiService;
import com.mayikt.base.BaseResponse;
import com.mayikt.constants.Constants;
import com.mayikt.member.feign.VerificaCodeServiceFeign;
import com.mayikt.member.input.dto.UserInpDTO;
import com.mayikt.member.mapper.UserMapper;
import com.mayikt.member.mapper.entity.UserEntity;
import com.mayikt.member.service.MemberRegisterService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;

@RestController
@Service
public class MemberRegisterServiceImpl extends BaseApiService<JSONObject> implements MemberRegisterService {
    @Autowired
    private VerificaCodeServiceFeign verificaCodeServiceFeign;
    @Autowired
    private UserMapper userMapper;

    @Override
    @Transactional
    public BaseResponse<JSONObject> register(@RequestBody UserInpDTO   userInpDTO, String registCode) {
        if (StrUtil.isEmpty(  userInpDTO.getUserName())){
            return setResultError("用户名不能为空");
        }
        if (StrUtil.isEmpty(  userInpDTO.getPassword())){
            return setResultError("密码不能为空");
        }
        if (StrUtil.isEmpty(  userInpDTO.getPassword())){
            return setResultError("手机号码不能为空");
        }
        if (StrUtil.isEmpty(registCode)){
            return setResultError("验证码不能为空");
        }
        BaseResponse<JSONObject> result = verificaCodeServiceFeign.verificaWeixinCode(  userInpDTO.getMobile(), registCode);
        if (!result.getCode().equals(Constants.HTTP_RES_CODE_200)){
            return setResultError(result.getMsg());
        }
        userInpDTO.setPassword(SecureUtil.md5(userInpDTO.getPassword()));
        UserEntity userEntity = new UserEntity();
        BeanUtils.copyProperties(userInpDTO,userEntity);
        userEntity.setCreateTime(LocalDateTime.now());
        userEntity.setUpdateTime(userEntity.getCreateTime());
        userEntity.setState(1);
        if(userMapper.insert(userEntity)>0){
            return setResultSuccess("注册成功");
        }else{
            return setResultError("注册失败");
        }
    }
}
